<?php
namespace app\common\model\newmodel;

use think\Model;
use app\common\model\newmodel\User as UserModel;
use think\Db;

class Factory extends Model
{
    protected $table = 'factory';
    protected $pk = 'id';

    /**
     * 工厂列表
     */
    public static function getFactoryList($page = 1, $pageSize = 10, $keyword = '')
    {
        $query = self::order('id desc');
        
        if (!empty($keyword)) {
            $query->where('factory_name', 'like', "%{$keyword}%");
        }
        
        $list = $query->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
        ]);
        
        return [
            'code' => 1,
            'msg' => 'success',
            'data' => [
                'total' => $list->total(),
                'per_page' => $list->listRows(),
                'current_page' => $list->currentPage(),
                'last_page' => $list->lastPage(),
                'data' => $list->toArray()['data']
            ]
        ];
    }

    /**
     * 添加工厂
     */
    public static function addFactory($data)
    {
        if (empty($data['factory_name']) || empty($data['address'])) {
            return ['code' => 0, 'msg' => '工厂名称和地址不能为空'];
        }

        // 检查工厂名称是否已存在
        $exists = self::where('factory_name', $data['factory_name'])->find();
        if ($exists) {
            return ['code' => 0, 'msg' => '工厂名称已存在'];
        }

        try {
            $factory = new self();
            $factory->factory_name = $data['factory_name'];
            $factory->address = $data['address'];
            $factory->save();
            
            return ['code' => 1, 'msg' => '添加成功', 'data' => $factory];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '添加失败：' . $e->getMessage()];
        }
    }

    /**
     * 修改工厂
     */
    public static function updateFactory($id, $data)
    {
        if (empty($id)) {
            return ['code' => 0, 'msg' => '工厂ID不能为空'];
        }

        $factory = self::get($id);
        if (!$factory) {
            return ['code' => 0, 'msg' => '工厂不存在'];
        }

        if (empty($data['factory_name']) || empty($data['address'])) {
            return ['code' => 0, 'msg' => '工厂名称和地址不能为空'];
        }

        // 检查工厂名称是否已存在（排除当前工厂）
        $exists = self::where('factory_name', $data['factory_name'])->where('id', '<>', $id)->find();
        if ($exists) {
            return ['code' => 0, 'msg' => '工厂名称已存在'];
        }

        try {
            $factory->factory_name = $data['factory_name'];
            $factory->address = $data['address'];
            $factory->save();
            
            return ['code' => 1, 'msg' => '修改成功'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '修改失败：' . $e->getMessage()];
        }
    }

    //单个工厂的管理员列表
    public static function factoryAdminList($factoryId='')
    {
        if(empty($factoryId)){
            return ['code'=>false,'msg'=>'参数不完整'];
        }
        $userIds=UserFactory::getUserIdsByFactoryId($factoryId);
        $userData=UserModel::whereIn('UserId',$userIds)->where('Role',301)->select()->toArray();
        return ['code' =>true, 'msg'=>$userData];
    }

    //添加工厂管理员
    public static function factoryAdminAdd($data)
    {
        if (empty($data['factoryId']) || empty($data['Iphone']) || empty($data['Name']) || empty($data['sex'])) {
            return ['code' => false, 'msg' => '参数不完整'];
        }
        
        $existUser = UserModel::where('Iphone', $data['Iphone'])
                        ->find();
        if ($existUser) {
            return ['code' => false, 'msg' => '手机号已存在'];
        }
        
        Db::startTrans();
        try {
            $user = new UserModel();
            $user->Iphone = $data['Iphone'];
            $user->Name = $data['Name'];
            $user->Sex = $data['sex'];
            $user->Role = 301;
            $user->State = 1;
            $user->save();
            UserFactory::addUserFactory($user->UserId, $data['factoryId']);
            Db::commit();
            return ['code' => true, 'msg' => '工厂管理员添加成功', 'data' => $user];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => false, 'msg' => $e->getMessage()];
        }
    }
    
}